<template>
  <div class="data-source-container">
    <div class="toolbar">
      <div class="left">
        <el-button type="primary" @click="handleCreateDataSource">
          <el-icon><Plus /></el-icon>新建数据源
        </el-button>
        <el-radio-group v-model="viewMode" class="view-mode">
          <el-radio-button label="table">
            <el-icon><List /></el-icon>
          </el-radio-button>
          <el-radio-button label="card">
            <el-icon><Grid /></el-icon>
          </el-radio-button>
        </el-radio-group>
      </div>
      <el-input
        v-model="searchQuery"
        placeholder="搜索数据源名称"
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 表格视图 -->
    <el-table
      v-if="viewMode === 'table'"
      :data="dataSourceList"
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="name" label="数据源名称" />
      <el-table-column prop="type" label="类型" />
      <el-table-column prop="host" label="主机地址" />
      <el-table-column prop="port" label="端口" width="100" />
      <el-table-column prop="database" label="数据库" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" link @click="handleViewTables(row)">
              查看表
            </el-button>
            <el-button
              type="primary"
              link
              :loading="row.testing"
              @click="handleTest(row)"
            >
              测试连接
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 卡片视图 -->
    <draggable
      v-if="viewMode === 'card'"
      v-model="dataSourceList"
      class="card-view"
      v-loading="loading"
      :group="{ name: 'datasources' }"
      item-key="id"
      handle=".drag-handle"
      @end="handleDragEnd"
    >
      <template #item="{ element: item }">
        <el-card class="data-source-card" :body-style="{ padding: '20px' }">
          <div class="card-header">
            <div class="card-title">
              <el-icon class="drag-handle"><Rank /></el-icon>
              <span class="name">{{ item.name }}</span>
              <el-tag :type="getStatusTagType(item.status)" size="small">
                {{ getStatusText(item.status) }}
              </el-tag>
            </div>
            <div class="card-type">
              <el-tag effect="plain">{{ item.type }}</el-tag>
            </div>
          </div>
          <div class="card-content">
            <div class="info-item">
              <span class="label">主机地址：</span>
              <span class="value">{{ item.host }}</span>
            </div>
            <div class="info-item">
              <span class="label">端口：</span>
              <span class="value">{{ item.port }}</span>
            </div>
            <div class="info-item">
              <span class="label">数据库：</span>
              <span class="value">{{ item.database }}</span>
            </div>
          </div>
          <div class="card-footer">
            <el-button-group>
              <el-button
                type="primary"
                :loading="item.testing"
                @click="handleTest(item)"
                size="small"
              >
                测试连接
              </el-button>
              <el-button type="primary" @click="handleEdit(item)" size="small">
                编辑
              </el-button>
              <el-button type="danger" @click="handleDelete(item)" size="small">
                删除
              </el-button>
            </el-button-group>
          </div>
        </el-card>
      </template>
    </draggable>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <DataSourceForm
      v-model:visible="formVisible"
      :edit-data="editingData"
      @submit="handleFormSubmit"
    />

    <DataSourceTables
      v-model:visible="tablesVisible"
      :data-source="currentDataSource"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { Plus, Search, List, Grid, Rank } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Draggable from "vuedraggable";
import DataSourceForm from "./components/DataSourceForm.vue";
import DataSourceTables from "./components/DataSourceTables.vue";
import {
  getDataSourceList,
  createDataSource,
  updateDataSource,
  deleteDataSource,
  testDataSourceConnection,
} from "@/api/dataSource";
import type { DataSource } from "@/types/dataSource";
import { DataSourceStatus } from "@/types/dataSource";

const loading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const formVisible = ref(false);
const editingData = ref<DataSource | null>(null);
const dataSourceList = ref<DataSource[]>([]);
const viewMode = ref<"table" | "card">("table");
const tablesVisible = ref(false);
const currentDataSource = ref<DataSource | null>(null);

const getStatusTagType = (status: DataSourceStatus) => {
  const types: Record<DataSourceStatus, string> = {
    [DataSourceStatus.Connected]: "success",
    [DataSourceStatus.Disconnected]: "info",
    [DataSourceStatus.Error]: "danger",
  };
  return types[status];
};

const getStatusText = (status: DataSourceStatus) => {
  const texts: Record<DataSourceStatus, string> = {
    [DataSourceStatus.Connected]: "已连接",
    [DataSourceStatus.Disconnected]: "未连接",
    [DataSourceStatus.Error]: "错误",
  };
  return texts[status];
};

const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      keyword: searchQuery.value,
      page: currentPage.value,
      pageSize: pageSize.value,
    };
    const { list, total: totalCount } = await getDataSourceList(params);

    // 从 localStorage 获取排序信息
    const savedOrder = localStorage.getItem("dataSourceOrder");
    if (savedOrder) {
      const orderMap = JSON.parse(savedOrder);
      // 应用保存的排序
      list.sort((a, b) => {
        const orderA = a.id
          ? orderMap[a.id] ?? Number.MAX_SAFE_INTEGER
          : Number.MAX_SAFE_INTEGER;
        const orderB = b.id
          ? orderMap[b.id] ?? Number.MAX_SAFE_INTEGER
          : Number.MAX_SAFE_INTEGER;
        return orderA - orderB;
      });
    }

    dataSourceList.value = list;
    total.value = totalCount;
  } catch (error) {
    console.error("加载数据源列表失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleCreateDataSource = () => {
  editingData.value = null;
  formVisible.value = true;
};

const handleEdit = (row: DataSource) => {
  editingData.value = row;
  formVisible.value = true;
};

const handleTest = async (row: DataSource) => {
  if (!row.id) return;

  row.testing = true;
  try {
    const { success, message } = await testDataSourceConnection(row.id);
    if (success) {
      ElMessage.success("连接测试成功");
      row.status = DataSourceStatus.Connected;
    } else {
      ElMessage.error(message || "连接测试失败");
      row.status = DataSourceStatus.Error;
    }
  } catch (error) {
    console.error("测试连接失败:", error);
    row.status = DataSourceStatus.Error;
  } finally {
    row.testing = false;
  }
};

const handleDelete = (row: DataSource) => {
  if (!row.id) return;

  ElMessageBox.confirm("确定要删除该数据源吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loading.value = true;
    try {
      await deleteDataSource(row.id);
      ElMessage.success("删除成功");
      loadData();
    } finally {
      loading.value = false;
    }
  });
};

const handleFormSubmit = async (data: DataSource) => {
  loading.value = true;
  try {
    if (data.id) {
      await updateDataSource(data.id, data);
      ElMessage.success("更新成功");
    } else {
      await createDataSource(data);
      ElMessage.success("创建成功");
    }
    loadData();
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  loadData();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadData();
};

watch([searchQuery], () => {
  currentPage.value = 1;
  loadData();
});

// 保存视图模式到 localStorage
watch(viewMode, (newMode) => {
  localStorage.setItem("dataSourceViewMode", newMode);
});

// 添加拖动排序相关的代码
const handleDragEnd = () => {
  // 保存新的排序到 localStorage
  const orderMap = dataSourceList.value.reduce((acc, item, index) => {
    if (item.id) {
      acc[item.id] = index;
    }
    return acc;
  }, {} as Record<number, number>);

  localStorage.setItem("dataSourceOrder", JSON.stringify(orderMap));
};

// 初始化时从 localStorage 读取视图模式
onMounted(() => {
  const savedMode = localStorage.getItem("dataSourceViewMode");
  if (savedMode === "table" || savedMode === "card") {
    viewMode.value = savedMode;
  }
  loadData();
});

const handleViewTables = (row: DataSource) => {
  currentDataSource.value = row;
  tablesVisible.value = true;
};
</script>

<style scoped>
.data-source-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar .left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.view-mode {
  margin-left: 16px;
}

.search-input {
  width: 300px;
}

.card-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.data-source-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-title .name {
  font-size: 16px;
  font-weight: 500;
}

.card-content {
  flex: 1;
  margin-bottom: 16px;
}

.info-item {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.info-item .label {
  color: var(--el-text-color-secondary);
  width: 80px;
}

.info-item .value {
  color: var(--el-text-color-primary);
}

.card-footer {
  display: flex;
  justify-content: flex-end;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.drag-handle {
  cursor: move;
  color: var(--el-text-color-secondary);
  margin-right: 8px;
}

.drag-handle:hover {
  color: var(--el-text-color-primary);
}

/* 拖动时的样式 */
.sortable-ghost {
  opacity: 0.5;
  background: var(--el-color-primary-light-9);
}

.sortable-drag {
  opacity: 0.9;
  background: var(--el-color-white);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 